package com.yichen.rent.service;

import java.util.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Selection;

import com.alibaba.fastjson.JSONArray;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import org.springframework.util.CollectionUtils;
import util.IdWorker;

import com.yichen.rent.dao.UserDao;
import com.yichen.rent.pojo.User;
import util.JwtUtil;

/**
 * 服务层
 * 
 * @author Administrator
 *
 */
@Service
public class UserService {

	@Autowired
	private UserDao userDao;
	
	@Autowired
	private IdWorker idWorker;

	@Autowired
	private JwtUtil jwtUtil;

	@Autowired
	private BCryptPasswordEncoder encoder;

	/**
	 * 查询全部列表
	 * @return
	 */
	public List<User> findAll() {
		return userDao.findAll();
	}

	
	/**
	 * 条件查询+分页
	 * @param whereMap
	 * @param page
	 * @param size
	 * @return
	 */
	public Page<User> findSearch(Map whereMap, int page, int size) {
		Specification<User> specification = createSpecification(whereMap);
		PageRequest pageRequest =  PageRequest.of(page-1, size);
		return userDao.findAll(specification, pageRequest);
	}

	
	/**
	 * 条件查询
	 * @param whereMap
	 * @return
	 */
	public List<User> findSearch(Map whereMap) {
		Specification<User> specification = createSpecification(whereMap);
		return userDao.findAll(specification);
	}

	/**
	 * 根据ID查询实体
	 * @param id
	 * @return
	 */
	public User findById(String id) {
		return userDao.findById(id).orElse(null);
	}

	/**
	 * 增加
	 * @param user
	 */
	public void add(User user) {
		user.setId( idWorker.nextId()+"" );
		user.setPassword(encoder.encode(user.getPassword()));
		userDao.save(user);
	}

	/**
	 * 修改
	 * @param user
	 */
	public void update(User user) {
		user.setPassword(encoder.encode(user.getPassword()));
		userDao.save(user);
	}

	/**
	 * 删除
	 * @param id
	 */
	public void deleteById(String id) {
		userDao.deleteById(id);
	}

	/**
	 * 动态条件构建
	 * @param searchMap
	 * @return
	 */
	private Specification<User> createSpecification(Map searchMap) {

		return new Specification<User>() {

			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicateList = new ArrayList<Predicate>();
                // 编号
                if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) {
                	predicateList.add(cb.equal(root.get("id").as(String.class), searchMap.get("id")));
                }
                // 姓名
                if (searchMap.get("username")!=null && !"".equals(searchMap.get("username"))) {
                	predicateList.add(cb.equal(root.get("username").as(String.class), searchMap.get("username")));
                }
                // 手机号
                if (searchMap.get("mobile")!=null && !"".equals(searchMap.get("mobile"))) {
                	predicateList.add(cb.equal(root.get("mobile").as(String.class), searchMap.get("mobile")));
                }

                // 我的关注
                if (searchMap.get("my_focus")!=null && !"".equals(searchMap.get("my_focus"))) {
                	predicateList.add(cb.like(root.get("my_focus").as(String.class), "%"+(String)searchMap.get("my_focus")+"%"));
                }
                // 最近联系
                if (searchMap.get("recent_contact")!=null && !"".equals(searchMap.get("recent_contact"))) {
                	predicateList.add(cb.like(root.get("recent_contact").as(String.class), "%"+(String)searchMap.get("recent_contact")+"%"));
                }
                // 浏览记录
                if (searchMap.get("browsing_history")!=null && !"".equals(searchMap.get("browsing_history"))) {
                	predicateList.add(cb.like(root.get("browsing_history").as(String.class), "%"+(String)searchMap.get("browsing_history")+"%"));
                }
                // 头像
                if (searchMap.get("avatar")!=null && !"".equals(searchMap.get("avatar"))) {
                	predicateList.add(cb.like(root.get("avatar").as(String.class), "%"+(String)searchMap.get("avatar")+"%"));
                }
                // 我的分享
                if (searchMap.get("my_share")!=null && !"".equals(searchMap.get("my_share"))) {
                	predicateList.add(cb.like(root.get("my_share").as(String.class), "%"+(String)searchMap.get("my_share")+"%"));
                }
                // 我的举报
                if (searchMap.get("my_report")!=null && !"".equals(searchMap.get("my_report"))) {
                	predicateList.add(cb.like(root.get("my_report").as(String.class), "%"+(String)searchMap.get("my_report")+"%"));
                }
				// 用户角色
				if (searchMap.get("usertype")!=null && !"".equals(searchMap.get("usertype"))) {
					predicateList.add(cb.equal(root.get("usertype").as(String.class), searchMap.get("usertype")));
				}
				
				return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));

			}
		};

	}


	public User login(String username, String password,String usertype) {
		Map<String,String> map = new HashMap<>();
		if (usertype!=null && !usertype.equals("用户")) {
			map.put("username",username);
			map.put("usertype",usertype);

		}else {
			map.put("username",username);
			map.put("usertype","用户");
		}

		this.findSearch(map);
		List<User> all = this.findSearch(map);
		if (!CollectionUtils.isEmpty(all)&& encoder.matches(password, all.get(0).getPassword())) {
			return all.get(0);
		}
		return null;
	}

	public void updatePassword(User user) {
		user.setPassword(encoder.encode(user.getPassword()));
		userDao.save(user);
	}

	public Map<String,Object> getInfo(String token) {
		Claims claims = jwtUtil.parseJWT(token);
		String id = claims.getId();
		String usertype = (String) claims.get("roles");
		User one = this.findById(id);
		List<String> list = new ArrayList<>();
		if (usertype.equals("系统管理员")) {
			list.add("admin");
		}
		if (usertype.equals("房东")) {
			list.add("house");
		}
		if (usertype.equals("经纪人")) {
			list.add("agent");
		}
		Map<String,Object> map1 = new HashMap<>();
		if (one!=null){
			map1.put("name",one.getUsername());
			map1.put("uid",one.getId());
			map1.put("mobile",one.getMobile());
			map1.put("avatar",one.getAvatar());
			map1.put("roles",list);
			return map1;
		}
		return null;
	}

	/**
	 * 获取关注房源
	 * @param uid
	 * @return
	 */
	public List<String> getFocus(String uid) {
		List<String> list = new ArrayList<>();
		Optional<User> userOptional = userDao.findById(uid);
		if (userOptional.isPresent()){
			User user = userOptional.get();
			String my_focus = user.getMy_focus();
			if (my_focus != null) {
				return JSONArray.parseArray(my_focus, String.class);
			}
		}
		return list;
	}
}
